<template>
    <div class="editproductPage">
            <div class="basic-info">基本信息</div> 
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"  >

            <el-form-item label="产品分类" prop="categoryId">
              <el-select
                @change="selectOrigin2"
                size="small"
                clearable
                v-model="ruleForm.categoryId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in List2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="产品类型" prop="type"  >
                <el-radio-group v-model="ruleForm.type"  >
                    <el-radio :label="0" >虚拟</el-radio>
                    <el-radio :label="1" >实物</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="产品编码" prop="goodId" placeholder="请填写SPU编码，来自于泰康之家/泰康拜博">
                <el-input v-model="ruleForm.goodId"></el-input>
            </el-form-item>
        <!-- </el-form> -->
        <!-- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> -->
            <el-form-item label="产品名称" prop="goodName" required placeholder="请填写名称">
                <el-input v-model="ruleForm.goodName"  style="width:500px;"  minlength="5" maxlength="30"></el-input>
            </el-form-item>
            <!-- <el-form-item label="产品来源" prop="channel" required>
                <el-select v-model="ruleForm.channel" placeholder="请选择活动区域">
                <el-option label="建投" value="A"></el-option>
                <el-option label="拜博" value="B"></el-option>
                </el-select>
            </el-form-item> -->

        <el-form-item label="产品来源" prop="channel">
            <el-select v-model="ruleForm.channel" placeholder="请选择(拜博/健投)" @change="selectOrigin">
                <el-option
                    v-for="item in placeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    ></el-option>
            <!-- <el-option label="建投" value="建投"></el-option>
            <el-option label="拜博" value="拜博"></el-option> -->
            </el-select>
        </el-form-item>

                <!-- <el-form-item label="产品主图" prop="picUrl" width="120">
                <template slot-scope="scope">
                    <img :src="scope.picUrl">
                </template>
                </el-form-item> -->
              <!-- <el-form-item label="商品图片" prop="pic">
            <el-upload
                class="avatar-uploader"
                :action="baseUrl + '/v1/addimg/food'"
                :show-file-list="false"
                :on-success="uploadImg"
                :before-upload="beforeImgUpload">
                <img v-if="foodForm.image_path" :src="baseImgPath + foodForm.image_path" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item> -->
        <el-row>
          <el-col :span="10">
            <el-form-item label="图片" prop="pic" required>
              <el-upload
                class="upload-demo"
                ref="upd"
                accept="image/png,image/jpeg"
                :action= setUrl
                :headers="headers"  
                :before-upload="beforeUpd"
                :on-error="errorUp"
                :on-success="successUp"
              >
                <el-button  type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，长度比为1:1,且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-col>
          </el-col>
          <el-col style="text-align:center" :span="14">
            
          </el-col>
          <img :src="img" style="width:100px;height:100px;" alt />
        </el-row>

                <div class="basic-info" style="margin-bottom: 20px;">产品信息</div> 

             <el-form-item label="产品描述" prop="description" >
                <el-input v-model="ruleForm.description"></el-input>
            </el-form-item>
            <el-form-item label="现价" prop="marketPrice">
                <el-input-number v-model="ruleForm.marketPrice" :min="0" :controls="false" :precision="2" required placeholder="小数点后保留2位"></el-input-number><span class="abs" >元</span>
            </el-form-item>
            <el-form-item label="划线价" prop="originalPrice"  type="number">
                <el-input-number v-model="ruleForm.originalPrice" :min="0" placeholder="要求大于现价" type="number" :controls="false" :precision="2"></el-input-number><span class="abs">元</span>
            </el-form-item>
            <el-form-item label="产品链接" prop="url" required>
                <el-input v-model="ruleForm.url"></el-input>
            </el-form-item>

            <div class="More-settings">更多设置</div>

            <el-form-item label="产品排序" prop="showOrder" >
                <el-input @input="ipt" v-model="ruleForm.showOrder" style="width:400px;" placeholder="整数，数字越小排序越靠前，相同数字，按照上架时间倒序"></el-input>
            </el-form-item>
            <el-form-item label="上架设置" prop="goodStatus">
                <el-radio-group v-model="ruleForm.goodStatus">
                    <el-radio :label="0">立即上架</el-radio>
                    <el-radio :label="2">定时上架</el-radio>
                     <el-date-picker
                            style="width:250px;margin-right:20px;"
                            v-model="ruleForm.showShelfTime"
                            @change="timechange1"
                            format="yyyy-M-dd h:mm:ss"
                            type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    <el-radio :label="1">暂不上架</el-radio>
                </el-radio-group>
            </el-form-item>     
            <el-form-item label="下架设置" prop="godown">
                <el-checkbox-group v-model="ruleForm.godown">
                <el-checkbox label="定时下架" style="margin-right:20px;"></el-checkbox>
                   <el-date-picker
                        @change="timechange2"
                        v-model="ruleForm.offShelfTime"
                        type="date"
                        format="yyyy-M-dd h:mm:ss"
                        placeholder="下架日期">
                </el-date-picker>
                </el-checkbox-group>
            </el-form-item>
             
            <el-form-item label="活动标签" prop="label" >
            <el-select
                    @change="selectOrigin1"
                    size="small"
                    clearable
                    v-model="ruleForm.label"
                    placeholder="请选择"
                >
                    <el-option
                    v-for="item in List"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>

            

            <el-form-item label="产品标签">
                <el-tag
                :key="index"
                v-for="(tag,index) in dynamicTags"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-autocomplete
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                :popper-append-to-body="false"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect"
                @keyup.enter.native="handleInputConfirm"
                @input="change"
              >
              </el-autocomplete>
              <el-button v-else class="button-new-tag" size="small" @click="showInput"
                >+ 新标签</el-button
              >
            </el-form-item>

             <el-form-item label='是否推广' prop="promotion">
              <el-radio-group v-model="ruleForm.promotion" @change="select2">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
            </el-form-item>
            </el-form>
    </div>
</template>

<script>
import goodsApi from "@/api/lejv/goods"
import setting from "@/settings"
import {getToken} from "@/utils/auth"
import {queryGoodsList,delGoods,sortGoods,updateGoods,queryGoodsdetail,batchGoods,editdateGoods} from "@/api/lejv/goods"
  export default {
    data () {
        var validatemarketPrice = (rule, value, callback) => {
            if (!value) {   
                callback(new Error('请填写现价'));
            } else {
            // if (value >= this.ruleForm.originalPrice){

            //   callback(new Error('划线价低于原价，请重新输入'));
            // }
                callback();
            }
        };
        var validateoriginalPrice = (rule, value, callback) => {
            if (!value) {   
                callback();
            }  else {
            if (value <= this.ruleForm.marketPrice){

                callback(new Error('划线价低于原价，请重新输入'));
            }
                callback();
            }
        
        };
         var checkUrl = (rule, value, callback) => { //自定义校验规则,验证网址是否输入正确
            if (this.ruleForm.url !== "") {
                let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])/;
                if (!reg.test(this.ruleForm.url)) {
                return callback(new Error("请填写http,https开头的产品链接"));
                }
                callback()
            } else {
                return callback(new Error("请填写产品链接"));
            }
         };
          
        return {
            baseUrl:'',
            setUrl:"",
            radio: '1',
            img:"",
            dynamicTags: [],
            inputVisible: false,
            inputValue: '',
            restaurants: [],
            label:"",
            headers:{'Authorization':getToken()},
            ruleForm:{
                type:'',
                goodId:"",  //编码
                goodName:"",
                channel:'',
                description:'',
                originalPrice:'',
                marketPrice:'',
                url:"",
                goodStatus:'',
            
                showShelfTime:'',
                offShelfTime:'',
                goodStatus:'',
                picUrl:'',
                label:'',
                godown:'',
                category:'',
                pic:'',
                categoryId:'',
                promotion:'',
                labelType: "0",

                shelfLabelDataList:[]

            },
             rules: {
                goodId: [
                  {
                    required: true,
                    message: "请填写SPU编码",
                    trigger: "blur",
                  },
                ],
                categoryId:[
                  { required: true,message: '请选择产品分类', trigger: "blur" },
                ],
                goodName: [
                    { required: true, message: '请输入产品名称', trigger: 'blur' },
                    // { min: 5, max: 30, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                channel: [
                    { required: true, message: '请选择建投或拜博', trigger: 'change'}
                ],
                marketPrice: [
                 
                    { validator: validatemarketPrice, required: true, trigger: "blur"},
                ],
                originalPrice:[
                    // { message: "划线价低于原价,请重新输入", trigger: "blur" },
                    { validator: validateoriginalPrice, trigger: "blur" },
                ],
                // },
                 url: [
                    { required: true,validator: checkUrl,trigger: "blur" }
                ],
                pic: [{ required: true, message: "请上传产品主图", trigger: "blur" }],
             },
                
            placeList: [
                {
                    value:"B",
                label:"拜博"
                },
                {
                    value:"A",
                label:"健投"
                }
            ],
            List:[
                // {value:"新品",label:"新品"},
                // {value:"促销",label:"促销"},
                // {value:"特价",label:"特价"},
                // {value:"限时",label:"限时"},
                // {value:"秒杀",label:"秒杀"}
                ],
            List2: [
              // { value: "养康", 
              //   label: "养康" ,
              
              // },
              // { value: "齿科", 
              //   label: "齿科" 
              // },
              // { value: "体检", 
              //   label: "体检" ,
              //   disabled: true
              // },
              // { value: "保险", 
              //   label: "保险",
              //   disabled: true
              // },
              // { value: "其他", 
              //   label: "其他",
              //   disabled: true
              // },
            ],
            isDetail:true, 
            id:'',
            isUpd: true, //隐藏图片
        };
    },
    created(){
        // this.setUrl = setting.host + "/file/image/auth"
        // this.setUrl = "https://tklifeac.mobile.taikang.com/file/image/auth"  //生产环境需改为https
        this.setUrl = window.location.host.indexOf('tk') != -1 ? (window.location.protocol + "//" + window.location.host + "/file/image/auth") : "http://tklifeacuat.mobile.taikang.com/file/image/auth"
        // console.log('------this.setUrl', this.setUrl)
        this.id = this.$route.params.editid;
        console.log(this.$route.params.editid)
        this.getlabel()
        this.getcategories()
        this.init();
        if(this.$route.params.editid){
            this.isDetail=true
        }else{

        }
       
    },
    filters:{
        channelFilter(channel){
            if(channel=="A") return "健投"
            if(channel=="B") return "拜博"   
        }
    },
    methods:{
          //产品标签接口
    getlabel(){

      goodsApi.getlabel(0).then(res=>{
        console.log(res.data)
        if(res.code == 0){
            console.log(res.data)
           this.List=res.data.map(item=>({
             value:item.id,
             label:item.labelName
           }))
          console.log(this.List)
        }
      }

      )

    },
     // 产品分类接口
    getcategories(){

      goodsApi.getcategories().then(res=>{
        console.log(res)
        if(res.code== 0){
           console.log(res.data)
           this.List2=res.data.map(item=>({
             value:item.id,
             label:item.categoryName
           }))
            console.log(this.List2)
            }
        }
          )
    },
     //推荐标签模糊查询
    getquery(name){
      let obj={
        labelType:"1",
        labelName: name
      }
      console.log(this.inputValue)
      if(this.inputValue){
        goodsApi.getquery(obj).then(res=>{
        if(res.data){
          this.restaurants=res.data.map(item=>({
            value:item.labelName,
            id:item.id
          }))
          let ipt = document.querySelectorAll(".el-input__inner")[12]
          ipt.blur()
          console.log(ipt)
          this.$refs.saveTagInput.focus()
        }

        console.log(res)
     })
      }
      
    },
    change(){
      if(this.timeout) {
        clearTimeout(this.timeout)
      }
      // wait = 800 为设定的时间, 可以根据需求指定
      this.timeout = setTimeout(() => {
        // 调用接口 处理逻辑
        this.getquery(this.inputValue)
      },800)

    },
        init(){
            console.log(this.id)
            // let str = '?id='+this.id
            goodsApi.queryGoodsdetail(this.id)
            .then(res=>{  
                 if(res.code == 0){  
                     console.log(res.data.categoryId) 
                     this.ruleForm.type=Number(res.data.type)
                     this.ruleForm.goodId=res.data.goodId
                     this.ruleForm.goodStatus= Number(res.data.goodStatus)
                     this.ruleForm.goodName=res.data.goodName
                     this.ruleForm.channel=res.data.channel
                     this.ruleForm.description=res.data.description
                     this.ruleForm.originalPrice=res.data.originalPrice/100
                     this.ruleForm.marketPrice=res.data.marketPrice/100
                     this.ruleForm.url=res.data.url
                     this.ruleForm.showOrder=res.data.showOrder
                     this.ruleForm.showShelfTime=res.data.showShelfTime
                     this.ruleForm.offShelfTime=res.data.offShelfTime
                     this.ruleForm.label=res.data.label
                     this.ruleForm.categoryId=res.data.categoryId
                     this.ruleForm.promotion=res.data.promotion
                    this.ruleForm.labelType=res.data.labelType
                    this.ruleForm.shelfLabelDataList=res.data.shelfLabelDataList
                    //  this.ruleForm.pic=res.data.pic
                    if(res.data.pic){
                        this.ruleForm.pic=res.data.pic

                    }else{
                        this.ruleForm.pic = ""
                    }
                    this.ruleForm.category=res.data.category
                     this.img=res.data.pic
                      if(this.ruleForm.offShelfTime){
                        this.ruleForm.godown=['定时下架']
                    }
                   let a= this.ruleForm.shelfLabelDataList.find(item=>
                        item.labelType=='0',
                        
                    )
                      let b= this.ruleForm.shelfLabelDataList.filter(item=>
                        item.labelType=='1',
                        
                    )
                    if(a){
                      this.label = a.labelName
                    }
                    if(b){
                      b.forEach(item=>{
                        this.dynamicTags.push(item.labelName)
                      })

                    }
                    console.log(this.ruleForm.shelfLabelDataList,b, this.dynamicTags)
                     }         
            })
        },
        ipt(){
            this.$forceUpdate()
        },
        //上传图片
        successUp(val) {
            // this.ruleForm.picUrl = val.slice(49);
            console.log(val)
            this.img = val
            this.ruleForm.pic=val
            console.log(this.ruleForm.picUrl);
            this.$refs.upd.clearFiles();
            this.isUpd = false;
            this.$message({
                type: "success",
                message: "上传成功!",
            });
        },
        //上传失败
    errorUp(val){
      this.$message({
        type: "error",
        message: "上传失败!",
      });
    },
         //上传图片验证
    beforeUpd(file) {
      // console.log(file);
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const fileType =
        testmsg.toLowerCase() === "jpg" ||
        testmsg.toLowerCase() === "jpeg" ||
        testmsg.toLowerCase() === "png";
      const fileLimit = file.size / 1024 < 500;
      if (!fileType) {
        this.$message({
          message: "上传图片只能是jpg / png 格式!",
          type: "error",
        });
        return false; //必须加上return false; 才能阻止
      }
      if (!fileLimit) {
        this.$message({
          message: "上传文件大小不能超过 500k!",
          type: "error",
        });
        return false;
      }
      return fileLimit || fileType;
    },
        selectOrigin1(val){
          this.ruleForm.shelfLabelDataList = this.ruleForm.shelfLabelDataList.filter(item=>item.labelType!="0")
            let index=this.List.findIndex(item=>
            item.value==val
            )
            this.ruleForm.label = this.List[index].label;
            // console.log(val,this.List,index);
            let obj ={
              labelType:"0",
              labelName:this.List[index].label,
              id:val
            }
            this.ruleForm.shelfLabelDataList.push(obj)
            console.log(this.ruleForm.shelfLabelDataList);
        },
        select2(val) {
        this.ruleForm.promotion = val;
        console.log(val);
        },
        timechange1:function(val){
            console.log(val)
            this.form.datestart=val
            console.log(this.form.datestart)
        },
        timechange2:function(val){
            console.log(val)
            this.ruleForm.offShelfTime=val
            console.log(this.ruleForm.offShelfTime)
        },
         uploadImg(res, file) {
            if (res.status == 1) {
                this.foodForm.image_path = res.image_path;
            }else{
                this.$message.error('上传图片失败！');
            }
    },
    	beforeImgUpload(file) {
            const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isRightType) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isRightType && isLt2M;
        },
        handleServiceAvatarScucess(res, file) {
            if (res.status == 1) {
                this.form.image_path = res.image_path;
            }else{
                this.$message.error('上传图片失败！');
            }
        },
          beforeAvatarUpload(file) {
                const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isRightType) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isRightType && isLt2M;
            },
            resetForm(formName) {
                this.$router.go("-1")
            },
             //选择来源
            selectOrigin(val){
                console.log(val);
                this.ruleForm.channel = val

            },
            
            selectOrigin2(val) {
              this.ruleForm.categoryId = val;
              console.log(val);
            },
             handleClose(tag) {

              this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
              this.ruleForm.shelfLabelDataList = this.ruleForm.shelfLabelDataList.filter(item => item.labelName != tag)
              console.log("000,",this.dynamicTags,tag,this.ruleForm.shelfLabelDataList)
        // this.dynamicTags.remove(this.dynamicTags.indexOf(tag));
      },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
     handleInputConfirm() {
        // let inputValue = this.inputValue;
        let obj=null
        if (this.inputValue) {
          this.dynamicTags.push(this.inputValue);
          obj={
            labelName:this.inputValue,
            labelType:"1"
          };
          if(this.ruleForm.labelId){
            obj.id = this.ruleForm.labelId
            this.ruleForm.labelId=""
          }
          this.ruleForm.shelfLabelDataList.push(obj)
        }
        this.inputVisible = false;
        this.inputValue = '';
        console.log(this.dynamicTags,this.ruleForm.shelfLabelDataList)

          this.getquery(this.dynamicTags[this.dynamicTags.length-1])


      },
     querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
       handleSelect(event) {
        console.log(event,this.ruleForm.shelfLabelDataList);
        this.ruleForm.labelId = event.id
        this.handleInputConfirm()
      },

            //调编辑接口
        submitForm(formName){
            console.log(this.ruleForm)
            let params = { 
                 "id": this.id,
                 "goodId":this.ruleForm.goodId,
                 "channel":this.ruleForm.channel,
                 "goodName":this.ruleForm.goodName,
                  "originalPrice": this.ruleForm.originalPrice ? this.ruleForm.originalPrice : "",
                 "marketPrice":this.ruleForm.marketPrice,
                 "pic":this.ruleForm.pic,
                 "url":this.ruleForm.url,
                 "type":this.ruleForm.type,
                 "description":this.ruleForm.description,
                 "goodStatus":this.ruleForm.goodStatus,
                 "showOrder":this.ruleForm.showOrder,
                 "showShelfTime":this.ruleForm.showShelfTime,
                 "offShelfTime":this.ruleForm.offShelfTime,
                 "label":this.ruleForm.label,
                 "category":this.ruleForm.category,
                 "categoryId":this.ruleForm.categoryId,
                 "promotion":this.ruleForm.promotion,
                  "shelfLabelDataList":this.ruleForm.shelfLabelDataList

            }
             this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          console.log(params);
          goodsApi.editdateGoods(params).then((res) => {
            if (res.code == 0) {
              this.$router.push("/goods/kind");
            } else if (res.code == 11202) {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          alert("请填写全信息再提交");
        }
      });
           
        }
      }
    }
</script>
<style scoped lang="scss">
.aditproductPage {
  padding-left: 20px;
}
.product-mode {
  padding-top: 15px;
  padding-bottom: 15px;
  margin-bottom: 30px;
  border-bottom: 1px solid lightgrey;
  span {
    height: 10px;
    padding-top: 150px;
  }
}
.basic-info {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 20px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom:  10px;
}
.product-type {
  margin-top: 20px;
  display: flex;
  .el-button {
    background: white;
    color: black;
    margin-right: 40px;
  }
}
.el-input {
  width: 300px;
}
.More-settings {
  background: rgb(228, 228, 228);
  padding-left: 30px;
  padding-top: 10px;
  padding-right: 30px;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px solid black;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
img {
  width: 60px !important;
  height: 60px !important;
  border: 1px solid black;
  position: absolute;
}
.block {
  margin-left: 100px;
}
.el-tag {
  margin-left: 10px;
  border: 1px solid lightgrey;
  color: black;
  background-color: white;
  line-height: 30px;
  height: 32px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 140px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
